#version 130

#define CORNER_SIZE 8.0
#define DBL_CORNER_SIZE 16.0

uniform float time;
uniform sampler2D tex;
uniform int chrrr;

in vec2 fragmentTexCoord;
out vec4 fragColor;

uniform vec4 visionColor   = vec4(0.22, 0.8, 0.08, 1.00);
uniform float lumThreshold = 0.4;
uniform float colorAmp     = 5.0;

float noise(vec2 coords, float var)
{
	return fract(sin(dot(coords, vec2(12.9898, 78.2330)) + var) * 43758.5453) - 0.5;
}

int saltPepper(vec2 coords, float var)
{
	float v1 = noise(coords, var);
	float v2 = noise((coords + v1) / 1.3813, var);

	if (v1 > 0.49 && v2 > 0.49) {
		return 1;
	} else if (v1 < -0.49 && v2 < -0.49) {
		return -1;
	} else {
		return 0;
	}
}

void main(void)
{
	vec2 size = textureSize(tex, 0);

	float radius = size.x / 4.0;
	float corner = radius - CORNER_SIZE;
	vec2 center1 = vec2(size.x / 3.0, size.y / 2.0);
	vec2 center2 = vec2(size.x / 3.0 * 2.0, size.y / 2.0);

	vec2 toC1 = fragmentTexCoord * size - center1;
	vec2 toC2 = fragmentTexCoord * size - center2;
	float distToC1 = length(toC1);
	float distToC2 = length(toC2);
	
	float whiteNoise = noise(fragmentTexCoord, time);
	int sap = saltPepper(fragmentTexCoord, time);

	if (distToC1 < radius || distToC2 < radius) {
		vec2 coords = fragmentTexCoord;

		if (chrrr == 1) { // Chrrr
			coords.x = coords.x + sin(570 * coords.y - 200 * time) * 0.05 + sin(2 * coords.y - 12 * time) * 0.01;
		} else { // Cssss
			coords += vec2(whiteNoise, whiteNoise) / 256;
		}

		vec4 color = texture(tex, coords);
		float lum = dot(color, vec4(0.299, 0.587, 0.114, 0.0));
		if (lum < lumThreshold) { // Gain
			color *= colorAmp;
		}

		if (distToC2 > corner && distToC1 > corner) {
			float percent = (CORNER_SIZE - ((distToC1 < distToC2) ? (distToC1 - corner) : (distToC2 - corner))) / CORNER_SIZE;
			fragColor = color * visionColor * percent + whiteNoise / 4;
		} else {
			if (sap == 1) {
				fragColor = vec4(1.0, 1.0, 1.0, 1.0);
			} else if (sap == -1) {
				fragColor = vec4(0.0, 0.0, 0.0, 1.0);
			} else {
				fragColor = color * visionColor + whiteNoise / 4;
			}
		}
	} else {
		fragColor = vec4(0.0, 0.0, 0.0, 1.0);
	}
	return;
}

